<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据采集 - DTU管理系统</title>
    <script src="js/toast.js"></script>
    <link rel="stylesheet" href="css/common.css">
    <style>
        /* 页面特有样式 */
        .config-section h3 {
            color: #667eea;
            font-size: 1.2rem;
        }

        .form-row {
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        }
        
        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .checkbox-group input[type="checkbox"] {
            width: auto;
            margin: 0;
        }

        .config-note {
            background: #f8f9fa;
            border-left: 4px solid #667eea;
            padding: 1rem;
            margin-bottom: 1rem;
            border-radius: 0 6px 6px 0;
        }
        
        .config-note p {
            margin: 0;
            font-size: 0.9rem;
            color: #666;
        }
        
        .status-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 5px;
        }
        
        .status-active {
            background: #28a745;
        }

    </style>
</head>
<body>
    <div class="header">
        <h1>数据采集</h1>
        <div class="breadcrumb">DTU管理系统 / 数据采集</div>
    </div>

    <div class="container">
        <!-- Tab导航 -->
        <div class="nav-tabs">
            <a href="index.html" class="nav-tab">首页</a>
            <a href="network.html" class="nav-tab">网络配置</a>
            <a href="serial.html" class="nav-tab">串口配置</a>
            <a href="collect.html" class="nav-tab active">数据采集</a>
            <a href="push.html" class="nav-tab">数据推送</a>
            <a href="at-command.html" class="nav-tab">AT命令</a>
            <a href="system.html" class="nav-tab">系统设置</a>
        </div>
        
        <!-- 采集参数配置 -->
        <div class="config-section">
            <h3>采集参数配置</h3>
            <form id="collect-form">
                <div class="form-group">
                    <div class="checkbox-group">
                        <input type="checkbox" id="auto-collect" checked>
                        <label for="auto-collect">启用自动采集</label>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="collect-interval">采集间隔(秒)</label>
                        <input type="number" id="collect-interval" value="30" min="1" max="3600">
                    </div>
                    <div class="form-group">
                        <label for="collect-retry-count">重试次数</label>
                        <input type="number" id="collect-retry-count" value="3" min="0" max="10">
                    </div>
                    <div class="form-group">
                        <label for="collect-retry-interval">重试间隔(秒)</label>
                        <input type="number" id="collect-retry-interval" value="5" min="1" max="60">
                    </div>
                </div>
                <div class="form-group">
                    <label>采集状态: 
                        <span class="status-indicator status-active" id="collect-status-indicator"></span>
                        <span id="collect-status-text">正在采集</span>
                    </label>
                </div>
                <button type="button" class="btn btn-primary" onclick="saveCollectConfig()">保存配置</button>
                <button type="button" class="btn btn-success" onclick="startCollect()">立即采集</button>
                <button type="button" class="btn btn-secondary" onclick="stopCollect()">停止采集</button>
            </form>
        </div>

        <!-- Modbus测试配置 -->
        <div class="config-section">
            <h3>Modbus测试配置</h3>
            <div class="config-note">
                <p>此配置仅用于测试Modbus通信是否正常，不会影响实际的数据采集设备。<br>
                实际采集设备请通过AT命令或MQTT下发进行配置。</p>
            </div>
            <form id="modbus-form">
                <div class="form-row">
                    <div class="form-group">
                        <label for="modbus-address">设备地址</label>
                        <input type="number" id="modbus-address" value="1" min="1" max="247">
                    </div>
                    <div class="form-group">
                        <label for="modbus-function">功能码</label>
                        <select id="modbus-function">
                            <option value="3" selected>读保持寄存器(03)</option>
                            <option value="4">读输入寄存器(04)</option>
                            <option value="1">读线圈状态(01)</option>
                            <option value="2">读离散输入(02)</option>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="modbus-start-addr">起始地址</label>
                        <input type="number" id="modbus-start-addr" value="0" min="0" max="65535">
                    </div>
                    <div class="form-group">
                        <label for="modbus-count">寄存器数量</label>
                        <input type="number" id="modbus-count" value="10" min="1" max="125">
                    </div>
                </div>
                <button type="button" class="btn btn-primary" onclick="saveModbusTestConfig()">保存测试配置</button>
                <button type="button" class="btn btn-secondary" onclick="testModbus()">测试Modbus</button>
            </form>
        </div>
    </div>

    <!-- Toast容器 -->
    <div class="toast-container" id="toast-container"></div>

    <script>

        // API请求封装
        async function apiRequest(url, method = 'GET', data = null) {
            try {
                const options = {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json',
                    }
                };

                if (data) {
                    options.body = JSON.stringify(data);
                }

                const response = await fetch(url, options);
                const result = await response.json();

                if (!response.ok) {
                    throw new Error(result.error?.message || '请求失败');
                }

                return result;
            } catch (error) {
                console.error('API请求错误:', error);
                showMessage(error.message, 'danger');
                throw error;
            }
        }

        // 数据采集相关函数
        async function saveCollectConfig() {
            const data = {
                auto_collect: document.getElementById('auto-collect').checked,
                interval: parseInt(document.getElementById('collect-interval').value),
                retry_count: parseInt(document.getElementById('collect-retry-count').value),
                retry_interval: parseInt(document.getElementById('collect-retry-interval').value)
            };

            try {
                await apiRequest('/api/collect', 'POST', data);
                showMessage('采集配置保存成功');
            } catch (error) {
                showMessage('保存失败: ' + error.message, 'danger');
            }
        }

        async function saveModbusTestConfig() {
            const data = {
                device_address: parseInt(document.getElementById('modbus-address').value),
                function_code: parseInt(document.getElementById('modbus-function').value),
                start_address: parseInt(document.getElementById('modbus-start-addr').value),
                register_count: parseInt(document.getElementById('modbus-count').value),
                serial_port: "rs485"
            };

            try {
                await apiRequest('/api/modbus-test', 'POST', data);
                showMessage('Modbus测试配置保存成功');
            } catch (error) {
                showMessage('保存失败: ' + error.message, 'danger');
            }
        }

        async function startCollect() {
            try {
                showMessage('开始数据采集...', 'info');
                const result = await apiRequest('/api/collect/start', 'POST');
                
                if (result.success) {
                    showMessage('数据采集已开始');
                    updateCollectStatus(true);
                } else {
                    showMessage('启动采集失败: ' + result.error, 'danger');
                }
            } catch (error) {
                showMessage('启动采集失败: ' + error.message, 'danger');
            }
        }

        async function stopCollect() {
            try {
                showMessage('停止数据采集...', 'info');
                const result = await apiRequest('/api/collect/stop', 'POST');
                
                if (result.success) {
                    showMessage('数据采集已停止');
                    updateCollectStatus(false);
                } else {
                    showMessage('停止采集失败: ' + result.error, 'danger');
                }
            } catch (error) {
                showMessage('停止采集失败: ' + error.message, 'danger');
            }
        }

        async function testModbus() {
            const data = {
                address: parseInt(document.getElementById('modbus-address').value),
                function_code: parseInt(document.getElementById('modbus-function').value),
                start_address: parseInt(document.getElementById('modbus-start-addr').value),
                count: parseInt(document.getElementById('modbus-count').value),
                serial_port: "rs485"
            };

            try {
                showMessage('正在测试Modbus连接...', 'info');
                const result = await apiRequest('/api/modbus/test', 'POST', data);
                
                if (result.result === 'success') {
                    showMessage(`Modbus测试成功！读取到${result.data.values.length}个寄存器值，值为: ${result.data.values.join(',')}`, 'success');
                    console.log('Modbus测试结果:', result.data);
                } else {
                    showMessage('Modbus测试失败: ' + result.error, 'danger');
                }
            } catch (error) {
                showMessage('测试失败: ' + error.message, 'danger');
            }
        }

        // 更新采集状态显示
        function updateCollectStatus(isActive) {
            const indicator = document.getElementById('collect-status-indicator');
            const text = document.getElementById('collect-status-text');
            
            if (isActive) {
                indicator.className = 'status-indicator status-active';
                text.textContent = '正在采集';
            } else {
                indicator.className = 'status-indicator status-inactive';
                text.textContent = '已停止';
            }
        }

        // 加载采集配置
        async function loadCollectConfig() {
            try {
                const config = await apiRequest('/api/collect');
                updateCollectDisplay(config);
            } catch (error) {
                console.error('加载采集配置失败:', error);
            }
        }

        // 加载Modbus测试配置
        async function loadModbusTestConfig() {
            try {
                const config = await apiRequest('/api/modbus-test');
                document.getElementById('modbus-address').value = config.device_address || 1;
                document.getElementById('modbus-function').value = config.function_code || 3;
                document.getElementById('modbus-start-addr').value = config.start_address || 0;
                document.getElementById('modbus-count').value = config.register_count || 10;
            } catch (error) {
                console.error('加载Modbus测试配置失败:', error);
            }
        }

        function updateCollectDisplay(config) {
            document.getElementById('auto-collect').checked = config.auto_collect || false;
            document.getElementById('collect-interval').value = config.interval || 30;
            document.getElementById('collect-retry-count').value = config.retry_count || 3;
            document.getElementById('collect-retry-interval').value = config.retry_interval || 5;
            
            // 更新采集状态
            updateCollectStatus(config.is_collecting || false);
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('数据采集页面已加载');
            
            // 加载配置
            loadCollectConfig();
            loadModbusTestConfig();
            
            // 定时刷新采集状态
            setInterval(async () => {
                try {
                    const status = await apiRequest('/api/collect/status');
                    updateCollectStatus(status.is_collecting || false);
                } catch (error) {
                    console.error('获取采集状态失败:', error);
                }
            }, 10000); // 每10秒刷新一次
        });
    </script>
</body>
</html>